package com.hsy.managemoney.modules.recommend;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.ViewSwitcher;

import com.deparse.dpframe.ui.fragment.DPBaseFragment;
import com.hsy.managemoney.R;
import com.hsy.managemoney.modules.view.viewpager.cn.androiddevelop.cycleviewpager.lib.CycleViewPager;
import com.hsy.managemoney.modules.view.viewpager.com.stevenhu.android.phone.bean.ADInfo;
import com.hsy.managemoney.modules.view.viewpager.com.stevenhu.android.phone.utils.ViewFactory;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2016/10/11.
 */
public class FragmentRecommend extends DPBaseFragment implements ViewSwitcher.ViewFactory {
    private List<ImageView> views = new ArrayList<ImageView>();
    private List<ADInfo> infos = new ArrayList<ADInfo>();
    private CycleViewPager cycleViewPager;

    private String[] imageUrls = {"http://img.taodiantong.cn/v55183/infoimg/2013-07/130720115322ky.jpg",
            "http://pic30.nipic.com/20130626/8174275_085522448172_2.jpg",
            "http://pic18.nipic.com/20111215/577405_080531548148_2.jpg",
            "http://pic15.nipic.com/20110722/2912365_092519919000_2.jpg",
            "http://pic.58pic.com/58pic/12/64/27/55U58PICrdX.jpg"};


    @Override
    protected int getFragmentLayout() {
        return R.layout.fragment_recommond;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        initViewPager();
        initSwitch();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onHandleMessage(Message msg) {

    }

    private void initViewPager() {
        configImageLoader();
        initialize();
    }

    private int currentSwitch = 0;
    private String[] switchText = {"1", "2", "3"};
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (1 == msg.what) {
                currentSwitch = next();
                updateSwitch();
            }
        }
    };

    private void updateSwitch() {
        switcher.setText(switchText[currentSwitch]);
    }

    private int next() {
        int flag = currentSwitch + 1;
        if (flag > switchText.length - 1) {
            flag = flag - switchText.length;
        }
        return flag;
    }

    private TextSwitcher switcher;

    private class MyTimer extends TimerTask {

        @Override
        public void run() {
            Message message = new Message();
            message.what = 1;
            handler.sendMessage(message);

        }
    }

    private void initSwitch() {
        switcher = findViewById(R.id.switcher);
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new MyTimer(), 1, 3000);//每3秒更新
        switcher.setFactory(this);
        switcher.setInAnimation(AnimationUtils.loadAnimation(getAttchedActivity(), R.anim.yyy_bottom_in));
        switcher.setOutAnimation(AnimationUtils.loadAnimation(getAttchedActivity(), R.anim.yyy_up_out));
    }

    @SuppressLint("NewApi")
    private void initialize() {

        cycleViewPager =
                (CycleViewPager) getChildFragmentManager().findFragmentById(R.id.fragment_cycle_viewpager_content);


        for (int i = 0; i < imageUrls.length; i++) {
            ADInfo info = new ADInfo();
            info.setUrl(imageUrls[i]);
            info.setContent("图片-->" + i);
            infos.add(info);
        }

        // 将最后一个ImageView添加进来
        views.add(ViewFactory.getImageView(getAttchedActivity(), infos.get(infos.size() - 1).getUrl()));
        for (int i = 0; i < infos.size(); i++) {
            views.add(ViewFactory.getImageView(getAttchedActivity(), infos.get(i).getUrl()));
        }
        // 将第一个ImageView添加进来
        views.add(ViewFactory.getImageView(getAttchedActivity(), infos.get(0).getUrl()));

        // 设置循环，在调用setData方法前调用
        cycleViewPager.setCycle(true);

        // 在加载数据前设置是否循环
        cycleViewPager.setData(views, infos, mAdCycleViewListener);
        //设置轮播
        cycleViewPager.setWheel(true);

        // 设置轮播时间，默认5000ms
        cycleViewPager.setTime(2000);
        //设置圆点指示图标组居中显示，默认靠右
//        cycleViewPager.setIndicatorCenter();
    }

    private CycleViewPager.ImageCycleViewListener mAdCycleViewListener = new CycleViewPager.ImageCycleViewListener() {

        @Override
        public void onImageClick(ADInfo info, int position, View imageView) {
            if (cycleViewPager.isCycle()) {
                position = position - 1;
            }

        }

    };

    /**
     * 配置ImageLoder
     */
    private void configImageLoader() {
        // 初始化ImageLoader
        @SuppressWarnings("deprecation")
        DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(R.mipmap.icon_stub) // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.mipmap.icon_empty) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.mipmap.icon_error) // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true) // 设置下载的图片是否缓存在内存中
                .cacheOnDisc(true) // 设置下载的图片是否缓存在SD卡中
                        // .displayer(new RoundedBitmapDisplayer(20)) // 设置成圆角图片
                .build(); // 创建配置过得DisplayImageOption对象

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getAttchedActivity()).defaultDisplayImageOptions(options)
                .threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory()
                .discCacheFileNameGenerator(new Md5FileNameGenerator()).tasksProcessingOrder(QueueProcessingType.LIFO).build();
        ImageLoader.getInstance().init(config);
    }

    @Override
    public View makeView() {

        TextView tv = new TextView(getAttchedActivity());
        tv.setText(switchText[currentSwitch]);
        tv.setTextColor(getResources().getColor(R.color.dp_color_666));
        tv.setSingleLine(true);
        tv.setTextSize(12);
        tv.setEllipsize(TextUtils.TruncateAt.END);
        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.gravity = Gravity.CENTER_VERTICAL;
        tv.setLayoutParams(lp);

        return tv;
    }
}
